package com.zyf.wjy.service;

import com.zyf.wjy.dao.PlantingPlanDao;
import com.zyf.wjy.entity.PlantingPlan;
import com.zyf.wjy.util.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 种植计划服务类
 */
@Service
public class PlantingPlanService {
    
    @Autowired
    private PlantingPlanDao plantingPlanDao;
    
    @Autowired
    private FieldService fieldService;
    
    /**
     * 查询所有种植计划
     */
    public List<PlantingPlan> findAll() {
        return plantingPlanDao.findAll();
    }
    
    /**
     * 根据ID查询
     */
    public PlantingPlan findById(Long id) {
        return plantingPlanDao.findById(id);
    }
    
    /**
     * 根据状态查询
     */
    public List<PlantingPlan> findByStatus(String status) {
        return plantingPlanDao.findByStatus(status);
    }
    
    /**
     * 根据地块ID查询
     */
    public List<PlantingPlan> findByFieldId(Long fieldId) {
        return plantingPlanDao.findByFieldId(fieldId);
    }
    
    /**
     * 保存种植计划
     */
    public PlantingPlan save(PlantingPlan plan) {
        if (plan.getId() == null) {
            plan.setPlanCode(CodeGenerator.generatePlanCode());
            plan.setCreateTime(LocalDateTime.now());
            plan.setStatus("pending"); // 默认计划中
        }
        return plantingPlanDao.save(plan);
    }
    
    /**
     * 删除种植计划
     */
    public boolean deleteById(Long id) {
        return plantingPlanDao.deleteById(id);
    }
    
    /**
     * 开始执行计划
     */
    public void startPlan(Long planId) {
        PlantingPlan plan = plantingPlanDao.findById(planId);
        if (plan != null && "pending".equals(plan.getStatus())) {
            plan.setStatus("executing");
            plantingPlanDao.save(plan);
            
            // 更新地块信息
            fieldService.updatePlanting(plan.getFieldId(), plan.getCropId(), plan.getCropName());
        }
    }
    
    /**
     * 完成计划
     */
    public void completePlan(Long planId) {
        PlantingPlan plan = plantingPlanDao.findById(planId);
        if (plan != null && "executing".equals(plan.getStatus())) {
            plan.setStatus("completed");
            plantingPlanDao.save(plan);
            
            // 清空地块种植信息
            fieldService.clearPlanting(plan.getFieldId());
        }
    }
    
    /**
     * 取消计划
     */
    public void cancelPlan(Long planId) {
        PlantingPlan plan = plantingPlanDao.findById(planId);
        if (plan != null) {
            plan.setStatus("cancelled");
            plantingPlanDao.save(plan);
        }
    }
}

